/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudexapps.swfspreadsheet.actions;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import uk.ljmu.qudexapps.swfspreadsheet.domain.Files;
import uk.ljmu.qudexapps.swfspreadsheet.domain.MdSchemaInstance;
import uk.ljmu.qudexapps.swfspreadsheet.utilities.ExcelManagement;

/**
 * POJO Action Class that manages the Spreadsheet generation
 * 
 * @author agustinamartinez
 * 
 */
public class GenerateSpreadsheetAction extends AbstractAction {
    private Logger log = Logger.getLogger(GenerateSpreadsheetAction.class);

    @SuppressWarnings("unchecked")
    public Event doExecute(RequestContext context) {
	boolean resultsOK;
	Files myFiles = null;
	try {
	    StringBuilder sb = new StringBuilder();
	    myFiles = (Files) context.getFlowScope().get("files");
	    String strType = String.valueOf(context.getFlowScope()
		    .get("typeSS"));
	    int typeSS = Integer.parseInt(strType);
	    sb.append("attachment;filename=");
	    if (typeSS == 0) {
		sb.append("collections-spreadsheet.xls");
	    } else {
		sb.append("files-spreadsheet.xls");
	    }
	    HttpServletResponse response = (HttpServletResponse) context
		    .getExternalContext().getNativeResponse();
	    response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-Disposition", sb.toString());

	    List<?> listMd = (List<?>) context.getFlowScope().get(
		    "schemasSelected");
	    // List<?> listDs = (List<?>)
	    // context.getFlowScope().get("datastreamsSelected");

	    // if (listMd == null || listDs == null)
	    if (listMd == null)
		return error();
	    
	    //Construct DDI if uploaded files
	    //if (myFiles.getZipFiles().size() > 0 && typeSS == 0) {
	//	this.parseDDI(myFiles.getZipFiles(), myFiles.getDdiObjectList());
	  //  }
	    ExcelManagement excelManager = new ExcelManagement();

	    resultsOK = excelManager.createExcelFile(
		    response.getOutputStream(),
		    (List<MdSchemaInstance>) listMd, typeSS, myFiles, myFiles.getTempDirPath());
	    // AMG - When working with streams this has to be called
	    context.getExternalContext().recordResponseComplete();

	    if (!resultsOK) {
		return error();
	    }
	    return success();
	} catch (IOException e) {
	    log.fatal(e.getMessage());
	    return error();
	} finally {
	    context.getExternalContext().recordResponseComplete();
	    if (myFiles != null) {
		if (myFiles.getZipFiles().size() > 0)
		    myFiles.cleanZipFiles();
		myFiles.cleanDDiObjects();
	    }
	}
    }
}
